<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="85px">
			<el-form-item label="智能柜编号" prop="cabinetCode">
				<el-input v-model="queryParams.cabinetCode" placeholder="请输入智能柜编号" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="智能柜名称" prop="cabinetName">
				<el-input v-model="queryParams.cabinetName" placeholder="请输入智能柜名称" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="所属库房" prop="storehouseId">
				<el-tree-select v-model="queryParams.storehouseId" :data="storehouseOptions"
					:props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择库房名称"
					clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="读写器IP" prop="rwIp">
				<el-input v-model="queryParams.rwIp" placeholder="请输入读写器IP" clearable @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="Plus" @click="handleAdd"
					v-hasPermi="['base:cabinet:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
					v-hasPermi="['base:cabinet:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
					v-hasPermi="['base:cabinet:remove']">删除</el-button>
			</el-col>
			<!-- <el-col :span="1.5">
				<el-button type="warning" plain icon="Download" @click="handleExport"
					v-hasPermi="['base:cabinet:export']">导出</el-button>
			</el-col> -->
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="cabinetList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="ID" align="center" prop="cabinetId" />
			<el-table-column label="智能柜编号" align="center" prop="cabinetCode" style="background-color: #E4E7ED;"
				width="100" />
			<el-table-column label="上级编号" align="center" prop="parentName" />
			<el-table-column label="智能柜名称" align="center" prop="cabinetName" width="100" />
			<el-table-column label="柜子类型" align="center" prop="leve">
				<template #default="scope">
					<dict-tag :options="base_cabinet_leve" :value="scope.row.leve" />
				</template>
			</el-table-column>
			<el-table-column label="库房" align="center" prop="storehouseName" />
			<el-table-column label="状态" align="center" prop="status">
				<template #default="scope">
					<dict-tag :options="bas_cabinet_status" :value="scope.row.status" />
				</template>
			</el-table-column>
			<el-table-column label="层数" align="center" prop="layerNum" />
			<el-table-column label="格数/层" align="center" prop="gridNum" />
			<el-table-column label="读写器IP" align="center" prop="rwIp" width="200" />
			<el-table-column label="读写器端口" align="center" prop="rwPort" width="100" />
			<el-table-column label="端口号" align="center" prop="gridPort" />
			<el-table-column label="监控摄像头IP" align="center" prop="cameraIp" width="120" />
			<el-table-column label="摄像头端口" align="center" prop="cameraPort" width="100" />
			<el-table-column label="摄像头账号" align="center" prop="cameraLogin" width="100" />
			<el-table-column label="监控摄像头密码" align="center" prop="cameraPassword" width="200" />
			<el-table-column label="描述" align="center" prop="describ" />
			<el-table-column label="排列顺序" align="center" prop="orderPort" width="200">
				<template #default="scope">
					<dict-tag :options="deposit_order_port" :value="scope.row.orderPort" />
				</template>
			</el-table-column>
			<el-table-column label="备注" align="center" prop="remark" />
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="360">
				<template #default="scope">
					<el-button type="text" icon="Edit" @click="handleNorms(scope.row)">设置规格</el-button>
					<el-button type="text" icon="Edit" @click="handleShow(scope.row)"
						v-hasPermi="['deposit:cabinet:showInfo']">查看智能柜详情</el-button>
					<el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['base:cabinet:edit']">修改</el-button>
					<el-button type="text" icon="Delete" @click="handleDelete(scope.row)"
						v-hasPermi="['base:cabinet:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改智能柜对话框 -->
		<el-dialog :title="title" v-model="open" width="900px" append-to-body>
			<el-form ref="cabinetRef" :model="form" :rules="rules" label-width="120px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="智能柜编号" prop="cabinetCode">
							<el-input v-model="form.cabinetCode" placeholder="后台自动生成" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="柜子类型" prop="leve">
							<el-select v-model="form.leve" placeholder="请选择柜子类型" @change="selectChange">
								<el-option v-for="dict in base_cabinet_leve" :key="dict.value" :label="dict.label"
									:value="parseInt(dict.value)"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="disabledInput">
						<el-form-item label="上级智能柜" prop="parentId">
							<el-select v-model="form.parentId" placeholder="请选择">
								<el-option v-for="item in cabinetOptions" :key="item.cabinetId" :label="item.cabinetName"
									:value="item.cabinetId"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="所属库房" prop="storehouseId">
							<el-tree-select v-model="form.storehouseId" :data="storehouseOptions"
								:props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
								placeholder="请选择库房名称" check-strictly />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="智能柜名称" prop="cabinetName">
							<el-input v-model="form.cabinetName" placeholder="请输入智能柜名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="读写器IP" prop="rwIp">
							<el-input v-model="form.rwIp" placeholder="请输入读写器IP" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="读写器端口" prop="rwPort">
							<el-input v-model="form.rwPort" placeholder="请输入读写器端口" />
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="!disabledInput">
						<el-form-item label="监控摄像头IP" prop="cameraIp">
							<el-input v-model="form.cameraIp" placeholder="请输入监控摄像头IP" />
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="!disabledInput">
						<el-form-item label="摄像头端口" prop="cameraPort">
							<el-input v-model="form.cameraPort" placeholder="请输入摄像头端口" />
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="!disabledInput">
						<el-form-item label="摄像头账号" prop="cameraLogin">
							<el-input v-model="form.cameraLogin" placeholder="请输入摄像头账号" />
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="!disabledInput">
						<el-form-item label="监控摄像头密码" prop="cameraPassword">
							<el-input v-model="form.cameraPassword" placeholder="请输入监控摄像头密码" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="排列顺序" prop="orderPort">
							<el-select v-model="form.orderPort" placeholder="请选择排列顺序">
								<el-option v-for="dict in deposit_order_port" :key="dict.value" :label="dict.label"
									:value="parseInt(dict.value)"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="柜子状态" prop="status">
							<el-select v-model="form.status" placeholder="请选择柜子状态">
								<el-option v-for="dict in bas_cabinet_status" :key="dict.value" :label="dict.label"
									:value="parseInt(dict.value)"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="描述" prop="describ">
							<el-input v-model="form.describ" placeholder="请输入描述" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 设置智能柜规格对话框 -->
		<el-dialog :title="titleSet" v-model="openSet" width="500px" append-to-body>
			<el-form ref="cabinetRefSet" :model="formSet" :rules="rulesSet" label-width="95px">
				<el-form-item label="智能柜编号" prop="cabinetCode">
					<el-input v-model="formSet.cabinetCode" placeholder="请输入智能柜编号" disabled />
				</el-form-item>
				<el-form-item label="智能柜名称" prop="cabinetName">
					<el-input v-model="formSet.cabinetName" placeholder="请输入智能柜名称" disabled />
				</el-form-item>
				<el-form-item label="层数" prop="layerNum">
					<el-input v-model.number="formSet.layerNum" placeholder="请输入层数" />
				</el-form-item>
				<el-form-item label="格数/层" prop="gridNum">
					<el-input v-model.number="formSet.gridNum" placeholder="请输入格数/层" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitFormSet">确 定</el-button>
					<el-button @click="canceled">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 查看详情对话框 -->
		<el-dialog :title="titleDetails" v-model="openShow" width="500px" append-to-body>
			<div class="head-container">
				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button type="info" size="small" plain icon="Sort" @click="detailsExpandAll">展开/折叠</el-button>
					</el-col>
				</el-row>
				<el-tree :data="shelvesOptions" :props="{ label: 'label', children: 'children' }"
					:expand-on-click-node="true" highlight-current :default-expand-all="detailsIsExpandAll" accordion
					v-if="showDetails" />
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="cancelShow">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="Cabinet">
import {
	listCabinet,
	getCabinet,
	delCabinet,
	addCabinet,
	updateCabinet,
	updateGridAndLayer,
	treeselectCabinet
} from "@/api/base/cabinet";
import {
	treeselectHouse
} from "@/api/deposit/storehouse";
import { ref } from "vue";
import { ElMessage } from 'element-plus';

const {
	proxy
} = getCurrentInstance();

const {
	deposit_order_port, base_cabinet_leve, bas_cabinet_status
} = proxy.useDict('deposit_order_port', 'base_cabinet_leve', 'bas_cabinet_status');

const validateCom = (rule, value, callback) => {
	const MIN_NUMBER = 1
	const one = Number(value)
	if (Number.isInteger(one)) {
		if (one < MIN_NUMBER) {
			return callback(new Error('输入值必须为大于0的正整数'))
		}
		return callback()
	}
	return callback(new Error('请输入数字值'))
}

const cabinetList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const shelvesOptions = ref(undefined);
const openSet = ref(false);
const titleSet = ref("");
const storehouseOptions = ref(undefined);
const cabinetOptions = ref([]);
const openShow = ref(false);
const titleDetails = ref("");
const detailsIsExpandAll = ref(false);
const showDetails = ref(true);
const disabledInput = ref("")


const data = reactive({
	form: {},
	formSet: {},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		cabinetCode: null,
		parentCode: null,
		cabinetName: null,
		storehouseId: null,
		describ: null,
		layerNum: null,
		gridNum: null,
		rwIp: null,
		rwPort: null,
		gridPort: null,
		leve: 0,
		cameraIp: null,
		cameraPort: null,
		cameraLogin: null,
		cameraPassword: null,
		status: null,
		delflag: null,
		orderPort: null,
		zcabinetId: null,
	},
	rules: {
		leve: [
			{ required: true, message: '请选择柜子类型', trigger: 'change' }
		],
		storehouseId: [
			{ required: true, message: '请选择所属库房', trigger: 'change' }
		],
	},
	rulesSet: {
		layerNum: [
			{ required: true, message: '层数不能为空', trigger: 'blur' },
			{ type: 'number', message: '输入只能为数字类型' },
			{ validator: validateCom, trigger: 'blur' }
		],
		gridNum: [
			{ required: true, message: '格数/层不能为空' },
			{ type: 'number', message: '输入只能为数字类型' },
			{ validator: validateCom, trigger: 'blur' }
		]
	}
});

const {
	queryParams,
	form,
	rules,
	formSet,
	rulesSet
} = toRefs(data);

/** 查询智能柜列表 */
function getList() {
	loading.value = true;
	listCabinet(queryParams.value).then(response => {
		cabinetList.value = response.rows;
		total.value = response.total;
		loading.value = false;
	});
}

// /** 查询智能柜下拉树结构 */
// function getTreeselect() {
// 	listCabinet().then(response => {
// 		cabinetOptions.value = [];
// 		const data = {
// 			cabinetId: 0,
// 			cabinetName: '顶级',
// 			children: []
// 		};
// 		data.children = proxy.handleTree(response.rows, "cabinetId", "parentId");
// 		cabinetOptions.value.push(data);
// 	});
// }

// 取消按钮
function cancel() {
	open.value = false;
	reset();
}

// 设置智能柜规格取消按钮
function canceled() {
	openSet.value = false;
	reset();
}

// 查看详情取消按钮
function cancelShow() {
	openShow.value = false;
}

// 表单重置
function reset() {
	form.value = {
		cabinetId: null,
		cabinetCode: null,
		parentCode: null,
		cabinetName: null,
		storehouseId: null,
		describ: null,
		layerNum: null,
		gridNum: null,
		rwIp: null,
		rwPort: null,
		gridPort: null,
		leve: null,
		cameraIp: null,
		cameraPort: null,
		cameraLogin: null,
		cameraPassword: null,
		status: 0,
		delflag: null,
		orderPort: null,
		zcabinetId: null,
		createBy: null,
		createTime: null,
		updateBy: null,
		updateTime: null,
		remark: null
	};
	proxy.resetForm("cabinetRef");
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm("queryRef");
	handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
	ids.value = selection.map(item => item.cabinetId);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
}

/** 查询库房下拉树结构 */
function getTreeselectStorehouse() {
	treeselectHouse().then(response => {
		storehouseOptions.value = response.data;
	});
};
/** 新增按钮操作 */
async function handleAdd() {
	reset();
	// await getTreeselect();
	getCabinet().then(response => {
		cabinetOptions.value = response.cabinets;
		open.value = true;
		title.value = "添加智能柜";
	});

}

/** 修改按钮操作 */
async function handleUpdate(row) {
	reset();
	// await getTreeselect();
	const cabinetId = row.cabinetId || ids.value
	getCabinet(cabinetId).then(response => {
		response.data.orderPort = Number(response.data.orderPort)
		form.value = response.data;
		open.value = true;
		title.value = "修改智能柜";
	});
}

/** 选择柜子 */
function selectChange(val) {
	if (val == 0) {
		disabledInput.value = false;
	} else {
		disabledInput.value = true;
		form.value.parentId = null
	}
}

/** 设置规格按钮操作 */
function handleNorms(row) {
	reset();
	const cabinetId = row.cabinetId || ids.value
	getCabinet(cabinetId).then(response => {
		formSet.value = response.data;
		openSet.value = true;
		titleSet.value = "设置智能柜规格";
	});
}

/** 查看详情 */
function handleShow(row) {
	const cabinetId = row.cabinetId || ids.value
	treeselectCabinet(cabinetId).then(response => {
		shelvesOptions.value = response.data;
		openShow.value = true;
		titleDetails.value = "查看智能柜详情"
	});
}

/** 详情展开/折叠操作 */
function detailsExpandAll() {
	if (shelvesOptions.value == "") {
		ElMessage.error('没有可供展开/折叠的结构')
	} else {
		showDetails.value = false;
		detailsIsExpandAll.value = !detailsIsExpandAll.value;
		nextTick(() => {
			showDetails.value = true
		})
	}
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs["cabinetRef"].validate(valid => {
		if (valid) {
			if (form.value.cabinetId != null) {
				updateCabinet(form.value).then(response => {
					proxy.$modal.msgSuccess("修改成功");
					open.value = false;
					getList();
				});
			} else {
				if (!disabledInput.value) {
					form.value.parentId = 0
				}
				addCabinet(form.value).then(response => {
					proxy.$modal.msgSuccess("新增成功");
					open.value = false;
					getList();
				});
			}
		}
	});
}


/** 设置规格提交按钮 */
function submitFormSet() {
	proxy.$refs["cabinetRefSet"].validate(valid => {
		if (valid) {
			const loading = ElLoading.service({
				lock: true,
				text: 'loading',
				background: 'rgba(0, 0, 0, .7)'
			})
			updateGridAndLayer(formSet.value).then(response => {
				if (response.code == 200) {
					proxy.$modal.msgSuccess("设置成功");
					openSet.value = false;
					loading.close();
					getList();
				} else {
					proxy.$modal.error("设置失败");
					openSet.value = false;
					loading.close();
					getList();
				}
			}).catch(() => {
				loading.close();
			});
		}
	});
}


/** 删除按钮操作 */
function handleDelete(row) {
	const cabinetIds = row.cabinetId || ids.value;
	proxy.$modal.confirm('是否确认删除智能柜编号为"' + cabinetIds + '"的数据项？').then(function () {
		return delCabinet(cabinetIds);
	}).then(() => {
		getList();
		proxy.$modal.msgSuccess("删除成功");
	}).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download('base/cabinet/export', {
		...queryParams.value
	}, `cabinet_${new Date().getTime()}.xlsx`)
}

getList();
getTreeselectStorehouse();
</script>
